<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="userName">
      <Input v-model="form.userName" placeholder="请输入用户名/手机号">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>
<script>
import * as API from "@/api/data.js"
import JSEncrypt from 'jsencrypt'
import {redisGet} from "@/api/data.js";
import {mapState} from 'vuex';

export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [
          {required: true, message: '账号不能为空', trigger: 'blur'}
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  data() {
    return {
      form: {
        userName: '',
        password: ''
      }
    }
  },
  computed: {
    rules() {
      return {
        userName: this.userNameRules,
        password: this.passwordRules
      }
    }
  },
  created() {
    this.getRedisDataByKey();
  },
  methods: {
    handleSubmit() {
      if (!sessionStorage.getItem('publicKey')) {
        this.getRedisDataByKey()
        setTimeout(()=>{
          if (!sessionStorage.getItem('publicKey')){
            this.$Message.warning("初始化密钥未找到，请确认是否生成已就绪。")
          }else{
            this.encryptPassword()
          }
        },1000)
      }else{
        this.encryptPassword()
      }
    },

    encryptPassword(){
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(sessionStorage.getItem('publicKey'));
      let params = Object.assign({}, this.form);
      params.password = encrypt.encrypt(params.password);
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$emit('on-success-valid', params)
        }
      })
    },

    //初始化获取RSA加密公钥
    getRedisDataByKey() {
      API.redisGet({key: "publicKey"}).then(res => {
        if (res.data) {
          sessionStorage.setItem('publicKey', res.data)
        }
      })
      API.redisGet({key: "userMap"}).then(res => {
        const data = res.data
        let redis = {
          userMap: data
        }
        this.$store.commit('setRedis', redis)
      })
      API.redisGet({key: "roleMap"}).then(res => {
        const data = res.data
        let redis = {
          roleMap: data
        }
        this.$store.commit('setRedis', redis)
      })
    },

  }
}
</script>
